﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ClassLibrary.Entity;
using ClassLibrary.DAO;
using System.IO;

public partial class en_ucControl_ucUploadImage : System.Web.UI.UserControl
{
    string _fileName = "";
    string _IdImage = "";
    TblImagesDAO imageDAO = new TblImagesDAO(Global.CONNECTION_STRING);
    TblAlbumImagesDAO AlbumDAO = new TblAlbumImagesDAO(Global.CONNECTION_STRING);
    TblAccountsDAO AcconntDAO = new TblAccountsDAO(Global.CONNECTION_STRING);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session[Global.SESSION_LOGGED_USER] != null)
            {
                LoadImageByAlbum();
                LoadPhotosname();
            }
            else
            {
                Response.Redirect("~/en/Default.aspx");
            }
            
        }

    }

    private void LoadPhotosname()
    {
        string IdAl = Request.QueryString["IdAl"];
        DataTable dt = AlbumDAO. GetAlbumsById(Convert.ToInt32(IdAl));
        foreach (DataRow dr in dt.Rows)
        {
            lblAlbumName.Text = dr["AlbumName"].ToString();
        }
        hypGetPhotoGroup.NavigateUrl = "~/en/GetCodePhotosGroups.aspx?IdAl=" + IdAl + "&keepThis=true&TB_iframe=true&width=700&height=170&ico=images/Get.png";
    }

    private void LoadImageByAlbum()
    {
        string IdAl = Request.QueryString["IdAl"];
        reImageByAlbum.DataSource = imageDAO.GetImageByIdAlbum(Convert.ToInt32(IdAl));
        reImageByAlbum.DataBind();
    }
    public void CheckAlbum()
    {

    }
    protected bool CheckAccountType()
    {
        bool flag = false;

        TblAccounts account = new TblAccounts();
        if (Session[Global.SESSION_LOGGED_USER] != null)
            account = (TblAccounts)Session[Global.SESSION_LOGGED_USER];

        TblAccounts userAccount = AcconntDAO.GetUser_Check(account.UsernameAcc);
        if (userAccount != null)
        {
            if (userAccount.TypeAcc == 2)
            {
                DataTable dt = null;

                dt = AlbumDAO.CheckNumberAlbum(Global.ConvertToInt(account.IDAcc.ToString()).ToString());
                int numberAlbum = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    numberAlbum += Convert.ToInt32(dr["numberAlbum"].ToString());
                }
                if (numberAlbum >= 1)
                {
                    flag = false; // khong cho insert them nữa
                }
                else
                {
                    flag = true;
                }
            }
            else if (userAccount.TypeAcc !=2 && userAccount.Display == true)
            {
                flag = true;
            }
        }
        return flag;
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        bool bFlag = false;
        string IdAl = Request.QueryString["IdAl"];
        string IdImg = Request.QueryString["IdImg"];
        lblInputCaptcha.Text = String.Empty;
        msCaptcha.ValidateCaptcha(txtCaptcha.Text);
        if (!msCaptcha.UserValidated)
        {
            lblInputCaptcha.Text = "Verification is Invalid";
            txtCaptcha.Text = String.Empty;
            lblInputCaptcha.ForeColor = System.Drawing.Color.Red;
            return;
        }
        try
        {
            //ktra Da co Album chua?


            TblAlbumImages Albumimage = new TblAlbumImages();
            TblAccounts account = new TblAccounts();
            if (Session[Global.SESSION_LOGGED_USER] != null)
                account = (TblAccounts)Session[Global.SESSION_LOGGED_USER];

            Albumimage.AlbumName = Global.ConvertToDate((DateTime.Now).ToString()) + "-" + account.IDAcc;
            Albumimage.DateCreate = DateTime.Now;
            Albumimage.IDAcc = ((TblAccounts)Session[Global.SESSION_LOGGED_USER]).IDAcc;
            Albumimage.Display = true;

            //Images
            TblImages image = new TblImages();
            image.DateUpload = DateTime.Now;
            
            image.Display = true;
            string filename = f_name.FileName;
            int fileSize = f_name.PostedFile.ContentLength;
            
            string path = Server.MapPath("~\\Admin\\img\\Images\\");

            if (IdAl == "" || IdAl == null)
            {
                if (CheckAccountType())
                {


                    DataTable dtAlbum = AlbumDAO.InsUpdTblAlbumImages(Albumimage, 1);
                    foreach (DataRow dr in dtAlbum.Rows)
                    {
                        IdAl = dr["IDAlbum"].ToString();
                    }

                    //insert Image
                    

                    image.IDAlbum = Convert.ToInt32(IdAl);
                    image.GetCode = "";
                    image.IDImage = 0;
                    image.DateUpload = DateTime.Now;

                    
                    if (IdImg == null || IdImg == "")
                    {
                        ////File size
                        //if (fileSize > 1050000)
                        //{
                        //    lb_message.Text = "Your file was not uploaded because it exceeds the 1 MB size limit.";
                        //    return;
                        //}

                        //// Get the extension of the uploaded file.
                        //string extension = System.IO.Path.GetExtension(_fileName);
                        //if (extension != ".jpg" && extension != ".bmp" && extension != ".png" && extension != ".gif" && extension != ".jpeg")
                        //{
                        //    lb_message.Text = "Your file was not uploaded because it does not have picture extension";
                        //    return;
                        //}
                        if (File.Exists(path + "\\" + filename))
                        {
                            lb_message.Text = "Trùng hình ảnh";
                            return;
                        }
                        f_name.SaveAs(path + "\\" + filename);
                        image.ImageURL = filename;
                        imageDAO.InsUpdImages(image, 1);
                    }
                    bFlag = true;

                }
                else
                {
                    ScriptManager.RegisterStartupScript(btnUpload, btnUpload.GetType(), "alert", "alert(' Your Account just create 1 Album and upload 5 Photos.!');", true);
                }
            }
            else 
            {
                //Kiem tra moi album chi co 5 hinh
                int IDAcc =((TblAccounts)Session[Global.SESSION_LOGGED_USER]).IDAcc;

                DataTable dtAlbum = AlbumDAO.Check5ImageInAlbum(IDAcc, Convert.ToInt32(IdAl));
                string SL = "";
                foreach (DataRow dr in dtAlbum.Rows)
                {
                    SL = dr["sl"].ToString();
                }
                if (Convert.ToInt32(SL) >= 5)
                {
                    lb_message.Text = "nhieu hon 5 photo";
                    return;
                }
                image.IDAlbum = Convert.ToInt32(IdAl);
                image.GetCode = "";
                image.IDImage = 0;
                if (IdImg == null || IdImg == "")
                {
                    ////File size
                    //if (fileSize > 1050000)
                    //{
                    //    lb_message.Text = "Your file was not uploaded because it exceeds the 1 MB size limit.";
                    //    return;
                    //}

                    //// Get the extension of the uploaded file.
                    //string extension = System.IO.Path.GetExtension(_fileName);
                    //if (extension != ".jpg" || extension != ".bmp" || extension != ".png" || extension != ".gif" || extension != ".jpeg")
                    //{
                    //    lb_message.Text = "Your file was not uploaded because it does not have picture extension";
                    //    return;
                    //}
                    if (File.Exists(path + "\\" + filename))
                    {
                        lb_message.Text = "Trùng hình ảnh";
                        return;
                    }
                    f_name.SaveAs(path + "\\" + filename);
                    image.ImageURL = filename;
                    imageDAO.InsUpdImages(image, 1);
                }
                bFlag = true;
            }
            
        }
        catch (Exception ex)
        {
            Session[Global.SESSION_ERROR] = ex;
            Response.Redirect(Global.ERROR_PAGE, true);
        }
        if (bFlag)
            Response.Redirect("~/en/Upload.aspx?idAl=" + IdAl);
            //ScriptManager.RegisterStartupScript(btnUpload, btnUpload.GetType(), "alert", "alert(' Sucessful.!');", true);
    }
    protected void lnkRefreshCaptcha_Click(object sender, EventArgs e)
    {
        txtCaptcha.Text = String.Empty;

    }
}
